var tableIns;
var searchParam = null;//用于存表单查询的条件参数
var selUploadRecordFileType = "";
var selIndex = "";
var selId = "";

layui.use(['form','layer','laydate','upload','table','laytpl','element'],function(){
    var element = layui.element;
    var laydate = layui.laydate;
    var upload = layui.upload;
    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'"+date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds+"'";
        return currentdate;
    }
    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min ={
                year:dates.year,
                month:dates.month-1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min:"1970-01-01",//设置min默认最小值
        max:getNowFormatDate,
        done:function (value,dates) {
            dateMin.config.max={
                year:dates.year,
                month:dates.month-1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds : 0
            }
        }
    });

    var form = layui.form,
        layer=layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    tableIns = table.render({
        id:"id",
        elem: '#recordsTable',
        url : baseUrl + '/records/queryRecordsByPackageIdPage',
        cellMinWidth : 95,
        page : true,
        where:{
            packageId:packageId,
            uploadRecordFileTypeStr:"speakingFlowStep"
        },
        request: {
            pageName: 'page' //页码的参数名称，默认：page
            ,limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },response: {
            statusName: 'code' //数据状态的字段名称，默认：code
            ,statusCode: 1 //成功的状态码，默认：0
            ,msgName: 'msg' //状态信息的字段名称，默认：msg
            ,countName: 'total' //数据总数的字段名称，默认：count
            ,dataName: 'records' //数据列表的字段名称，默认：data
        },loading: true
        ,page: {
            id:"id",
            limit: 10
            ,limits: [10, 20, 30, 40, 50]
            ,curr: 1
            ,groups: 5
            ,theme: '#5FB878'
            ,first: '首页'
            ,last: '尾页'
            ,prev: '<em><i class="layui-icon">&#xe603;</i></em>'
            ,next: '<em><i class="layui-icon">&#xe602;</i></em>'
            ,layout: [ 'prev', 'page', 'next', 'skip','count']
        },
        cols : [[
            {field: 'name', title: '名称', width:120,minWidth:120},
            {field: 'content', title: '内容', align:'center', width:330,minWidth:120},
            {field:'',align:'center',minWidth:250,width:300, title: '通话录音/状态',templet:function (d) {
                if(d.hadUploadFile == true && d.recordFileUrl!=null && d.recordFileUrl!="") {
                    return "<audio name='audio' style='width: 200px;height: 27px;' preload='none' class='videoArea' controlslist='nodownload' " +
                        "src='"+d.recordFileUrl+"' controls='controls' ></audio>";
                }else{
                    return "";
                }
            }},
            {field:'',align:'center',minWidth:120,width:120, title: '下载' , templet:function (d) {
                if(d.hadUploadFile == true && d.recordFileUrl!=null && d.recordFileUrl!=""){
                    return "<a href='javascript:void(0)' onclick=\"down('"+d.recordFileUrl+"')\" ><i class=\"layui-icon\" style=\"font-size:25px;\">&#xe601;</i></a>"
                }else{
                    return ""
                }
            }},
            {title: '操作', templet:'#recordBar',fixed:"right",align:"center",width:285,minWidth:285}
        ]],done: function(res, curr, count){
            intTableColorChange();
            // uploadFun(d);
        }
        ,text: {
            none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
        }
    });


    //列表操作
    table.on('tool(recordsTable)', function(obj){
        var layEvent = obj.event,
            param = obj.data;
        if(layEvent === 'composeSpeech'){ //合成语音
            layer.confirm('如有语音文件则会进行覆盖操作，你确定要进行合成语音？',{icon:3, title:'提示信息'},function(index){
                var load = layer.msg('执行中，请稍候',{icon: 16,time:false,shade:0.8});
                $.ajax({
                    type: "POST",
                    url:  baseUrl+'/records/composeSpeechById?id='+param.id+'&uploadRecordFileTypeStr='+param.uploadRecordFileType+"&index="+param.index,
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);
                        layer.close(load);
                        if(data==true){
                            reloadTable();
                        }else{
                            layer.msg("保存失败");
                        }
                        layer.close(index);
                    },
                    error: function () {
                        layer.close(load);
                        layer.msg("保存失败");
                        layer.close(index);
                    }
                });
            });
        }else if(layEvent === 'view'){//查看详情
            if(param.type==null || param.type==""){
                var winName = self.frameElement.getAttribute('id');
                console.log(winName);
                window.parent.layer.open({
                    type: 2,
                    title: '查看详情',
                    area: ['57%', '70%'],
                    /*btn: ['确 定', '取 消']
                    , yes: function (index, layero) {
                        //获取iframe层的提交按钮对象
                        var submitButton = layer.getChildFrame('button', index);
                        //我点!
                        submitButton.click();
                    }
                    , btn2: function (index, layero) {
                        layer.msg("取消保存")
                    },*/
                    content:[baseUrl+"/knowledgeBase/editKnowledgeBase?id="+param.id+"&brotherWinName="+winName]//no表示没有滚动条模式
                });
            }else{
                editSpeakingFlowStep(true,param.id,param.type,param.packageId,param.flowId);
            }
        }else if(layEvent == 'upload'){//上传文件处理
            uploadFun(param);
        }
    });


    // 提交查询条件表单
    form.on('submit(query)', function(data){
        searchParam = data.field;
        reloadTable();
    });


    //选中行时，高亮显示
    function intTableColorChange(){
        $(".layui-table-body tr").click(function(e){
            $(".layui-table-body  tr ").css("background","");
            $(this).css("background","#e6e6e6");
        });
    }

    //上传EXCEL
    var uploadFun = function(d){
        console.log(d.uploadRecordFileType);
        console.log(d);
        selUploadRecordFileType = d.uploadRecordFileType;
        selId = d.id;
        selIndex = d.index;
            $("#realUpload").attr("lay-data","{data:{'uploadType':'"+selUploadRecordFileType+"','id':'"+selId+"','index':'"+selIndex+"'}}");
            $("#realUpload").click();
    };


    var uploadInst = upload.render({
        elem: '#realUpload'
        ,url: baseUrl+'/recordFile/uploadRecordFileAndSaveCodeNum'//?uploadType='+selUploadRecordFileType+"&id="+selId+"&index="+selIndex
        ,method : "post"
        ,accept: 'file' //普通文件
        ,multiple: true
        ,before: function(obj){
            window.parent.layer.load(); //上传loading
        }
        ,done: function(res) {
            if (res.code <= 0) {
                window.parent.layer.msg(res.msg);
            } else {
                window.parent.layer.msg("上传成功.");
            }
            window.parent.layer.closeAll('loading'); //关闭loading
        }
        ,error:function (e) {
            window.parent.layer.msg("上传异常！！！");
            window.parent.layer.closeAll('loading'); //关闭loading
        }
    });

});


//重新加载table的数据
function reloadTable() {
    var load = layer.load();
    var whereParam = {};
    if(searchParam!=null){
        if(searchParam["name"] == ""){
            delete searchParam["name"];
        }
        if(searchParam["uploadRecordFileTypeStr"] == ""){
            layer.close(load);
            layer.msg("请选择类型再查询");
            return;
        }
        whereParam = searchParam;
    }
    console.log(getLength(whereParam));
    if(whereParam==null || getLength(whereParam) == 0 ){
        whereParam["packageId"] = packageId;
        var uploadRecordFileType=$("#uploadRecordFileType").val();
        console.log(uploadRecordFileType);
        if(uploadRecordFileType==undefined || uploadRecordFileType=="" || uploadRecordFileType==null){
            uploadRecordFileType = $("#uploadRecordFileType").val("speakingFlowStep")
        }else{
            whereParam["uploadRecordFileTypeStr"] = uploadRecordFileType;
        }
    }
    tableIns.reload({
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: whereParam
    });
    layer.close(load);
}


/**
 * 下载录音文件
 * @param url
 */
function down(url){
    //由于无法实现直接在后台判断下载权限，（无权限提示时无法实现） 只能现在最外层实现
    //判断下载权限
    var $eleForm =$("<a href='"+url+"' download=''></a>");
    $(document.body).append($eleForm);
    //提交表单，实现下载
    $eleForm[0].click();
}

//编辑默认分支
function editSpeakingFlowStep(edit,id,type,packageId,flowId){
    var params = "?flowId="+flowId+"&packageId="+packageId+"&stepId="+id+"&type="+type;
    var width = "50%";
    var higth = "89%";
    if(type != "c"){
        width = "50%";
        higth = "83%";
    }
    currentIndex = layer.open({
        title : "查看详情",
        type : 2,
        content : [baseUrl+"/flowConfig/saveOrUpdateSpeakingFlowStep"+params],
        resize:true,
        maxmin:false,
        isOutAnim:true,
        scrollbar:true,
        area : [width,higth]
    });
}

function getLength(obj){
    var count = 0;
    for(var i in obj){
        count++;
    }
    return count;
}
